//
//  GRMessageManger.m
//  Gree+
//
//  Created by 许金秧的IMAC  on 2017/7/3.
//  Copyright © 2017年 gree. All rights reserved.
//

#import "GRMessageManger.h"
#import "GRMessageView.h"


#define MARGIN 8
@interface GRMessageManger ()

@property (nonatomic, strong) GRWindow * window;
@property (nonatomic, strong) GRMessageView * messageView;
@property (nonatomic, assign) NSInteger timeout;
@property(nonatomic,strong) NSTimer *timer;

@end

@implementation GRMessageManger


+ (GRMessageManger *)shareInstance {
    static GRMessageManger * messageManger = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        messageManger = [[GRMessageManger alloc] init];
    });
    return messageManger;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initSubviews];
    }
    return self;
}

- (void)initSubviews {
    
    if (_window) {
        return;
    }
    _timeout = 3;
    _window = [[GRWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _window.windowLevel = UIWindowLevelAlert;
    [self.window makeKeyAndVisible];
    self.window.hidden = YES;
    
    _messageView = [[GRMessageView alloc] init];
    [_messageView setContentCompressionResistancePriority:(UILayoutPriorityRequired) forAxis:(UILayoutConstraintAxisHorizontal)];
    [_messageView setContentCompressionResistancePriority:(UILayoutPriorityRequired) forAxis:(UILayoutConstraintAxisVertical)];
    [_window addSubview:_messageView];
    
    [_messageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_window.mas_centerX);
        make.width.lessThanOrEqualTo(_window.mas_width).offset(-MARGIN*4);
        make.height.lessThanOrEqualTo(_window.mas_height).offset(-MARGIN*4);
        make.bottom.mas_equalTo(_window).offset(-49 -MARGIN);
    }];
    
    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(willStop)];
    [self.window addGestureRecognizer:tapGesture];
}


- (void)setTimeout:(NSInteger)timeout {
    _timeout = timeout;
}

- (void)start {
    
    self.window.hidden = NO;
    [self.window setNeedsLayout];
    [self.window layoutIfNeeded];
    
    self.messageView.alpha = 0;
    self.messageView.transform = CGAffineTransformMakeScale(0.5, 0.5);
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.messageView.alpha = 1;
        weakSelf.messageView.transform = CGAffineTransformMakeScale(1, 1);
    } completion:^(BOOL finished) {
    }];
    
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    if (_timeout>0) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:_timeout target:self selector:@selector(stop) userInfo:nil repeats:NO];
    }
}

- (void)willStop {
    if (_timeout>0) {
        [self stop];
    }
}

- (void)stop {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.messageView.alpha = 0;
    } completion:^(BOOL finished) {
        [self setImage:nil];
        [self setContent:nil];
        weakSelf.window.hidden = YES;
    }];
}

- (void)setImage:image {
    
    _messageView.imageView.image = image;
    [_messageView setNeedsUpdateConstraints];
    [_messageView updateConstraintsIfNeeded];
    [_messageView layoutIfNeeded];
}

- (void)setContent:(NSString *)content {
    _messageView.contentLabel.text = content;
    //
    //    CGSize size = [content boundingRectWithSize:CGSizeMake(SCREEN_WIDTH, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil].size;
    //
    //    _window.width = size.width + 100;
    //    _window.height = size.height + 30 +8 + 8  + 30 + 30;
    //    _window.centerX = SCREEN_WIDTH / 2;
    //    _window.centerY = SCREEN_HEIGHT / 2;
    
    
    [_messageView setNeedsUpdateConstraints];
    [_messageView setNeedsLayout];
    [_messageView layoutIfNeeded];
}

- (void)setContent:(NSString *)content andImage:(UIImage *)image {
    [self setImage:image];
    [self setContent:content];
}

+ (void)showMessage:(NSString *)message withImage:(UIImage *)image timeout:(NSInteger)timeout {
    dispatch_async(dispatch_get_main_queue(), ^{
        
        GRMessageManger * messageManger = [GRMessageManger shareInstance];
        messageManger.timeout = timeout;
        [messageManger setContent:message andImage:image];
        [messageManger start];
    });
}

+ (void)showMessage:(NSString *)message {
    [self showMessage:message withImage:nil];
}

+ (void)showMessage:(NSString *)message withImage:(UIImage *)image {
    [self showMessage:message withImage:image timeout:2];
}

+ (void)showMessage:(NSString *)message timeout:(NSInteger)timeout
{
    [self showMessage:message withImage:nil timeout:timeout];
}

@end
